#include "translationmanager.h"
#include "defines.h"

#include <QDebug>

TranslationManager *TranslationManager::instance_ = 0;

TranslationManager::TranslationManager(QObject *parent) :
    QObject(parent)
{
  instance_ = this;

  langPath = RESOURCE_DIR + "lang/";

  QDir langDir(langPath);
  QStringList langList = langDir.entryList(QStringList() << "*.qm");
  for (int i = 0; i < langList.count(); i++)
  {
    QString name = langList.at(i).toLower();
    name.remove("ste_");
    name.remove(".qm");
    langMap[name] = name;
  }

  langMap["en"] = "English (Default)";

  QFile mapFile(langPath + "lang.map");
  if (mapFile.open(QFile::ReadOnly))
  {
    QTextStream ts(&mapFile);
    while (!ts.atEnd())
    {
      QString line = ts.readLine().simplified();
      if (line.isEmpty())
        continue;

      //qDebug() << line;

      QStringList sl(line.split(QRegExp("\\s+"), QString::SkipEmptyParts));
      if (sl.count() > 1 && langMap.contains(sl.first()))
      {
        QString key(sl.first());
        sl.removeFirst();
        langMap[key] = sl.join(" ");
      }
    }
  }
}

void TranslationManager::translate(const QString &lang)
{
  qtTranslator.load("qt_" + lang,
          QLibraryInfo::location(QLibraryInfo::TranslationsPath));
  qApp->installTranslator(&qtTranslator);

  myappTranslator.load("ste_" + lang, langPath);
  qApp->installTranslator(&myappTranslator);
}

QIcon TranslationManager::icon(const QString &lang)
{
  QPixmap ico(langPath + "flags/" + lang + ".png");
  return QIcon(ico);
}
